using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class app_frame : System.Web.UI.MasterPage
{
    public security hdds;
    public string message;

    public string homepageURL = "";
    public string sRedirect = "";

    protected void Page_PreInit(object sender, EventArgs e)
    {
        //this.ContentPlaceHolder2.th = Session["Theme"].ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        LoadReminders(); // Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts
        CheckRightsForTask(); // Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts
        // For Header 03-Sep-2007        
        manageCollapsiblePanel();
        setPageTitle();
        if (!Page.IsPostBack)
        {
            managePoweredByMaxBlox();
            setLogo();
            manageADs();
            manageEmbedCodes();
            showFeedBackOption();
            manageMenuSearch();

            getnavigatorURL();
            getLogoutLink();
            ahomepagelink.HRef = homepageURL;
            alogout.HRef = sRedirect;
            GetFeedBackEmailIds();
            CreateAdditionalSectioninHeader(); // Added by srivatsan for next step and related info in Page Header
            /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
            BindControl BC = new BindControl();
            HDDatabase Hdd = new HDDatabase();
            DataTable dt = new DataTable();
            dt = Hdd.GetDataTable("select mem_id, mem_name from sy_acr_mem where acr_id='a1f7486385b04df0' order by mem_seq");
            ddl_deferred.DataSource = dt;
            ddl_deferred.DataTextField = "mem_name";
            ddl_deferred.DataValueField = "mem_id";
            ddl_deferred.DataBind();
            ddl_deferred.Items.Insert(0, new ListItem("--Select--", ""));
            Hdd = null;
            BC = null;
            /********* End of Task & Alerts *********/
        }
       
        this.hdds = new security(Session["userid"].ToString());
        if (!IsPostBack)
        {

            if (!Request.RawUrl.Contains("displayhelp.aspx"))
                mn_main = this.hdds.load_menu(mn_main);
            else
            {
                LinkButton1.Visible = false;
                //LinkButton2.Visible = false;
                //LinkButton3.Visible = false;
                imghome.Visible = false;
                imglogout.Visible = false;
                

                //LinkButton3.Text = "<img alt='Close' src='images/" + Session["Theme"].ToString().ToLower().Replace("theme","") + "/logout.jpg' style='border:0'/>";

                //LinkButton3.OnClientClick = "javascript:window.close()";
            }

            mn_main.MaximumDynamicDisplayLevels = 10;
        }

        if (lbl_user_name != null)
        {
            //lbl_user_name.Text = Session["user_name"].ToString();// +(Session["user_role"] == null ? "" : ("<br><b>Role</b>:&nbsp;" + Session["user_role"].ToString()));
            lbl_user_name.Text = Session["Welcome_Title"] == null ? "" : Session["Welcome_Title"].ToString(); // Modified by 'Imran Gani' on 07-Jan-2013, for dynamic welcome title.
            if (!IsPostBack)
            {
                security se = new security();
             //   mn_recentvisit = se.loadLastAccessedMenu(mn_recentvisit);
                //mn_quick_links = se.loadQuickLinks(mn_quick_links);
                //if (HttpContext.Current.Session["roleid"] != null)
                //    if (HttpContext.Current.Session["roleid"].ToString() == "377e55cec8d53d7d" || HttpContext.Current.Session["roleid"].ToString() == "e7029dafbe379f85")
                if (Session["roleid"] != null)
                    if (Session["roleid"].ToString() != "")
                    {
                        //quicklink.Text = "test";

                        //quicklink.Text="<div style=\"width: 186px;\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width: 186px;\">        <tr>            <td colspan=\"2\" style=\"height:2px;\">            </td>        </tr>        <tr class=\"ParentLink\">            <td style=\"padding-left:2px;text-align:left;\">$caption$            </td>            <td style=\"text-align:right;padding-right:2px;\">$img$            </td>        </tr>            </table>        <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width: 186px\">        <tr class='ChildLink'>            <td colspan=\"2\" style=\"height:2px;\">            </td>                    </tr>        <tr class='ChildLink'>            <td style=\"padding-left:2px;text-align:left;\">$image$            </td>            <td style=\"text-align:left;\">$content$            </td>        </tr>           </table>        <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width: 186px\">        <tr class='ChildLink'>            <td style=\"height:2px;\">            </td>                    </tr>           </table> </div>";
                    //    quicklink.Text = se.loadQuickLinks().ToString();

                        //quicklink.Text = quicklink.Text + " test data";
                    }
               // if (quicklink.Text.Trim() == "") ql.Visible = false;
            }
        }
        if (Request.QueryString["pgs_id"] != null)
        {
            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();
        }
        if (Request.QueryString["mn"] != null) //added by Prithi on 21-Aug-2008
        {
            string strfinal = "";
            load_menuname(Request.QueryString["mn"].ToString(), ref strfinal);

            ltaccordian.Text = strfinal;

        }

        if (Request.QueryString["ViewMode"] != null) // Added by 'Imran Gani' on 16-Jan-2013, to view content only.
            HttpContext.Current.Session["View_Mode"] = Request.QueryString["ViewMode"];
        if (Session["View_Mode"] != null && Session["View_Mode"].ToString() == "content")
        {
            tbl_hdr.Visible = false;
            sidepanel.Visible = false;
            td_CollapsePanel.Visible = false;
            tbl_acc_hd.Visible = false;
        }
        // Added by 'Imran Gani' on 10-Apr-2013, to view content with menu and loge.
        if (Session["View_Mode"] != null && Session["View_Mode"].ToString() == "content_with_menu")
            tbl_icons.Visible = false;

        ////code added by Sampath for IPP on 07-Jan-2011
        //if (Session["client_application"] != null)
        //{
        //    if (Session["client_application"].ToString().ToLower() == "ipp")
        //    {
        //        hfsourceapp.Value = "ipp";
        //        applyIPPchanges();
        //    }
        //    else
        //        findAndDisableMenu("Import From IPP");
        //}
        //else
        //    findAndDisableMenu("Import From IPP");
    }

    /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
    public void CheckRightsForTask()
    {
        HDDatabase HDD = new HDDatabase();
        security hdds = new security();
        bool Isview = false;

        string strRights = HDD.GetColumnValue("select mem_value1 from sy_acr_mem where acr_id='aa2e64b26eb2484d'");
        if (strRights != "")
        {
            if (strRights == "true" || strRights == "1")
            {
                Isview = hdds.getObjectRightsForUser("ob_task_config", "read");
                if (Isview == true)
                {
                    div_Notification.Style.Add("display", "block");
                    img_reminder.Style.Add("display", "block");
                }
                else
                {
                    div_Notification.Style.Add("display", "none");
                    img_reminder.Style.Add("display", "none");
                }
            }
            else
            {
                div_Notification.Style.Add("display", "none");
                img_reminder.Style.Add("display", "none");
            }
        }
    }

    public bool LoadReminders()
    {
        // user_id = Session["user_afrowid"].ToString();
        GenerateAlerts GA = new GenerateAlerts();
        try
        {
            GA.GenerateAlert();
            Reminders.DataSource = null;
            Reminders.DataSource = new DataView(GA.getTaskReminderData());
            Reminders.DataBind(); 
            //Reminders = GA.LoadGrid(Reminders);
            for (int i = 0; i < Reminders.Rows.Count; i++)
            {
                CheckBox chk_Select = new CheckBox();
                chk_Select.ID = "chk_Select_Reminders_" + i.ToString();
                chk_Select.Attributes.Add("onclick", "javascript:enableReminderButton();");
                Reminders.Rows[i].Cells[0].Controls.Add(chk_Select);
            }
            int count = Reminders.Rows.Count;
            if (Reminders.Rows.Count <= 0)
            {
                img_reminder.Visible = false;
                ReminderCount.Visible = false;
                // Remindera.Visible = false;
                ShowReminderList.Style.Add("display", "none");
            }
            else
            {
                img_reminder.Visible = true;
                ReminderCount.Visible = true;
            }
            ReminderCount.InnerText = count.ToString();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("appframe: Load Task Error: " + ex.Message);
        }
        finally
        {
            GA = null;
        }
        return true;
    }
    /********* End of Task & Alerts *********/

    ////function added by Sampath for IPP changes on 07-Jan-2011
    //private void applyIPPchanges()
    //{
    //    try
    //    {
    //        //hide logout button for IPP
    //        alogout.Visible = false;
    //        LinkButton1.Visible = false;

    //        mb_ltAds1.Visible = false;
    //        mb_ltAds2.Visible = false;

    //        //hide change password
    //        findAndDisableMenu("Change Password");

    //        //hide help menu
    //        findAndDisableMenu("Help");

    //        findAndDisableMenu("Role Setup");

    //        findAndDisableMenu("Import From QuickBooks&#0174;");

    //        findAndDisableMenu("Export Commissions");

    //        //if (mn_main.Items[5] != null)
    //        //{
    //        //    if (mn_main.Items[5].ChildItems[4] != null)
    //        //    {
    //        //        if (mn_main.Items[5].ChildItems[4].Text.ToLower() == "change password")
    //        //        {
    //        //            mn_main.Items[5].ChildItems.RemoveAt(4);
    //        //        }
    //        //    }
    //        //}


    //        //if (mn_main.Items[7] != null)
    //        //{
    //        //    if (mn_main.Items[7].Text.ToLower() == "help")
    //        //    {
    //        //        mn_main.Items.RemoveAt(7);
    //        //    }
    //        //}
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("appframe: applyIPPchanges: Error: " + ex.Message);
    //    }
    //}

    //private void findAndDisableMenu(string menuName)
    //{
    //    try
    //    {
    //        bool found = false;
    //        //traversing in menu item
    //        foreach (MenuItem mi in mn_main.Items)
    //        {
    //            if (mi.Text.ToLower() == menuName.ToLower())
    //            {
    //                mn_main.Items.Remove(mi);
    //                found = true;
    //                break;
    //            }
    //        }

    //        //traversing in menu child items
    //        if (!found)
    //        {
    //            foreach (MenuItem mi in mn_main.Items)
    //            {
    //                foreach (MenuItem miCh in mi.ChildItems)
    //                {
    //                    if (miCh.ChildItems.Count > 0)
    //                    {
    //                        foreach (MenuItem miCh1 in miCh.ChildItems)
    //                        {
    //                            if (miCh1.Text.ToLower() == menuName.ToLower())
    //                            {
    //                                miCh.ChildItems.Remove(miCh1);
    //                                found = true;
    //                                break;
    //                            }
    //                        }
    //                    }
    //                    else
    //                    {
    //                        if (miCh.Text.ToLower() == menuName.ToLower())
    //                        {
    //                            mi.ChildItems.Remove(miCh);
    //                            found = true;
    //                            break;
    //                        }
    //                    }
    //                }
    //                if (found) break;
    //            }
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("appframe: findAndDisableMenu: Error: " + ex.Message);
    //    }
    //}

    //private void setLogo()
    //{
    //    if (IsPostBack) return;//logic for transparent and large images
    //    ltrl_logo.Text = "<div class='backs'></div>";
    //    string temp = "url('images/LightBlue/logo.gif');";
    //    DynamicDisplayI ddi = new DynamicDisplayI();
    //    HDDatabase hddLogo = null;
    //    security s = null;
    //    try
    //    {
    //        if (Session["company_afrowid"] != null)
    //        {
    //            DirectoryInfo di = new DirectoryInfo(Server.MapPath(".") + "\\Images\\CustomLogo");
    //            FileInfo[] fis = di.GetFiles(Session["company_afrowid"].ToString()+"*");
    //            if (fis.Length > 0)
    //            {
    //                temp = "url('images/CustomLogo/" + fis[0].Name + "')";
    //                //ltrl_logo.Text = "<img src='Images/CustomLogo/" + fis[0].Name + "' />";
    //                ltrl_logo.Text = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/CustomLogo/" + fis[0].Name + "');background-repeat:no-repeat;></td></tr></table>";
    //            }
    //            else//if another user in the same company logs out
    //            {
    //                if (Session["hasCustomLogo"] != null)
    //                {
    //                    string fName = ""; string ext = "";
    //                    s = new security();
    //                    s.createCustomLogo(ref fName, ref ext);
    //                    ltrl_logo.Text = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/CustomLogo/" + Session["company_afrowid"] + ext + "'); background-repeat:no-repeat;></td></tr></table>";
    //                }
    //            }
    //        }
    //        //HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, "td_logo");
    //        //htc.Style.Add("background",temp);
    //    }
    //    catch (Exception e)
    //    {

    //    }
    //    finally 
    //    {
    //        hddLogo = null;
    //        ddi = null;
    //        s = null;
    //    }
    //}

    private void setLogo()
    {
        security s = null;
        try
        {
            if (IsPostBack) return;//logic for transparent and large images
            s = new security();
            s.setLogo(ref ltrl_logo);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SetLogo : " + ex.Message);
        }
        finally
        {
            s = null;
        }
    }
    private void managePoweredByMaxBlox()
    {
        if (IsPostBack) return;
        try
        {
            if (Session["poweredbymaxblox"] != null)//to use session once the data is fetched
            {
                ltrl_powered.Text = Session["poweredbymaxblox"].ToString();
            }
            else
            {
                Session["poweredbymaxblox"] = "";//optimization to fetch only once - sanal 3/2/11
                HDDatabase hdd = new HDDatabase();
                DataTable dt = hdd.GetDataTable("select * from sy_acr_mem where af_row_id='51f626f9c154bed5'");
                hdd = null;
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["mem_value1"].ToString().ToLower() == "true" || dt.Rows[0]["mem_value1"].ToString() == "1")
                        {
                            //ltrl_powered.Text = "<span class='controlFont' style='color: gray;'>Powered by MaxBlox</span>";
                            ltrl_powered.Text = dt.Rows[0]["mem_value2"].ToString();
                            Session["poweredbymaxblox"] = dt.Rows[0]["mem_value2"].ToString();
                        }
                        else
                        {
                            ltrl_powered.Text = "";
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in managePoweredByMaxBlox. " + e.Message);
        }
    }
    private void manageMenuSearch()
    {
        if (IsPostBack) return;
        try
        {
            if (hfMenuSearch.Value != "1")
            {
                HDDatabase hdd = new HDDatabase();
                DataTable dt = hdd.GetDataTable("select mem_value1 from sy_acr_mem where af_row_id='1bccadc4b3b277e1'");
                hdd = null;
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["mem_value1"].ToString().ToLower() == "true" || dt.Rows[0]["mem_value1"].ToString() == "1")
                        {
                            hfMenuSearch.Value = "1";
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageMenuSearch. " + e.Message);
        }
    }
    private void showFeedBackOption()
    {
        //return;
        if (IsPostBack) return;
        feedbackdivtrigger.Visible = false;
        div_feedback.Visible = false;
        try
        {
            if (Session["showfeedback"] != null)//to use session once the data is fetched
            {
                if (Session["showfeedback"].ToString()=="true")
                {
                    feedbackdivtrigger.Visible = true;
                    div_feedback.Visible = true;
                    div_feedback.Style.Add("display", "none");//to avoid flickering                    
                }
                else
                {
                    feedbackdivtrigger.Visible = false;
                    div_feedback.Visible = false;                  
                }
            }
            else
            {
                HDDatabase hdd = new HDDatabase();
                DataTable dt = hdd.GetDataTable("select * from sy_acr_mem where af_row_id='3e7357b3af6b74e1'");
                hdd = null;
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["mem_value1"].ToString().ToLower() == "true" || dt.Rows[0]["mem_value1"].ToString() == "1")
                        {
                            feedbackdivtrigger.Visible = true;
                            div_feedback.Visible = true;
                            div_feedback.Style.Add("display", "none");//to avoid flickering
                            Session["showfeedback"] = "true";
                        }
                        else
                        {
                            feedbackdivtrigger.Visible = false;
                            div_feedback.Visible = false;
                            Session["showfeedback"] = "false";

                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in showFeedBackOption. " + e.Message);
        }
    }
    private void setPageTitle()
    {
        //if (IsPostBack) return;
        try
        {
            if (Session["pageTitle"] != null)
            {
                Page.Header.Title = Session["pageTitle"].ToString();
            }
            else
            {
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini"))
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini");
                    Session["pageTitle"] = sr.ReadLine();
                    Page.Header.Title = Session["pageTitle"].ToString();
                    sr.Close();
                    sr = null;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setPageTitle function. Error: " + e.Message);
        }
    }
    private void manageADs()
    {
        if (IsPostBack) return;
        mb_ltAds1.Text = "&nbsp;";
        //mb_ltAds2.Text = "&nbsp;";
        //return;
        //lblAD.Text="&nbsp;";
        try
        {
            if (Session["mbAds"] != null)
            {
                if (Session["mbAds"].ToString() == "0")
                    return;
            }
            HDDatabase hddAD = new HDDatabase(Session["servercon"].ToString());
            string str = "";
            //for (int i = 0; i < Session.Keys.Count; i++)
            //    str = Session.Keys[i].ToString();
            //////////DataTable dt = hddAD.GetDataTable("select * from ngcompany where company_id='" + Session["company_id"].ToString() + "'");
            //////////dt = hddAD.GetDataTable("select * from AD_Manager where company_id='" + dt.Rows[0]["af_row_id"].ToString() + "' and show_ads=1 order by sequence");
            DataTable dt = hddAD.GetDataTable("select * from AD_Manager where company_id in (select af_row_id from ngcompany where company_id='" + Session["company_id"].ToString() + "') and show_ads=1 order by sequence");
            if (dt == null)
            {
                hddAD = null;
                //lblAD.Text = "&nbsp;";
                return;
            }
            if (dt.Rows.Count > 0)
            {
                Session["mbAds"] = "1";
                ////////string[] locations = new string[] { "tdcAD1", "tdcAD2" };
                ////////setAD(dt, locations);
                Control[] contrls = new Control[] { mb_ltAds1, mb_ltAds2 };
                setAD_New(dt, contrls);
                //if (dt.Rows[0]["show_ads"].ToString().ToLower() == "true")
                //{


                //DynamicDisplayI ddi = new DynamicDisplayI();
                //for (int j = 0; j < locations.Length; j++)
                //{
                //    HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, locations[j]);
                //    htc.Controls.Add(new LiteralControl(dt.Rows[j]["ad_code"].ToString()));
                //}
                //ddi = null;
                //lblAD.Text = dt.Rows[0]["ad_code"].ToString();
                //}
            }
            else
            {
                Session["mbAds"] = "0";
                hddAD = null;
                //lblAD.Text = "&nbsp;";
                return;
            }
            //hddAD = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageADs function. Error: " + e.Message);
            //lblAD.Text = "&nbsp;";
        }
    }
    private void manageEmbedCodes()
    {
        if (IsPostBack) return;
        try
        {
            HDDatabase hddEmbed = new HDDatabase(Session["servercon"].ToString());
            string str = "";
            //for (int i = 0; i < Session.Keys.Count; i++)
            //    str = Session.Keys[i].ToString();
            DataTable dt = hddEmbed.GetDataTable("select * from sy_embed_codes");
            if (dt == null)
            {
                hddEmbed = null;
                return;
            }
            if (dt.Rows.Count > 0)
            {
                setEmbedCode(dt);
            }
            else
            {
                hddEmbed = null;
                return;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageEmbedCodes function. Error: " + e.Message);
        }
    }
    private void setEmbedCode(DataTable dtEmbedCode)
    {
        if (dtEmbedCode == null) return;
        if (!dtEmbedCode.Columns.Contains("code")) return;
        if (dtEmbedCode.Rows.Count < 1) return;
        //DynamicDisplayI ddi = new DynamicDisplayI();
        string content = "";
        try
        {
            foreach (DataRow dr in dtEmbedCode.Rows)
            {
                content += dr["code"].ToString();
            }
            embed_code_literal.Text = content;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setEmbedCode function. Error: " + e.Message);
        }
        finally
        {
            //ddi = null;
        }
    }
    //private void setAD(DataTable dtAd, string[] locations)
    //{
    //    if (dtAd == null) return;
    //    if (dtAd.Rows.Count < 1) return;
    //    DynamicDisplayI ddi = new DynamicDisplayI();
    //    try
    //    {
    //        for (int j = 0; j < locations.Length; j++)
    //        {
    //            DataRow[] drs = dtAd.Select("sequence=" + Convert.ToString(j + 1));
    //            if (drs.Length > 0)
    //            {
    //                HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, locations[j]);
    //                htc.Controls.Add(new LiteralControl(drs[0]["ad_code"].ToString()));
    //            }
    //        }
    //    }
    //    catch (Exception e)
    //    {
    //        LogWriter.WriteLog("Error in setAD function. Error: " + e.Message);
    //    }
    //    finally
    //    {
    //        ddi = null;
    //    }
    //}
    private void setAD_New(DataTable dtAd, Control[] controls)
    {
        if (dtAd == null) return;
        if (dtAd.Rows.Count < 1) return;
        //DynamicDisplayI ddi = new DynamicDisplayI();
        try
        {
            for (int j = 0; j < controls.Length; j++)
            {
                DataRow[] drs = dtAd.Select("sequence=" + Convert.ToString(j + 1));
                if (drs.Length > 0)
                {
                    //HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, locations[j]);
                    //htc.Controls.Add(new LiteralControl(drs[0]["ad_code"].ToString()));
                    if (controls[j] is Literal)
                    {
                        Literal l = (Literal)controls[j];
                        l.Text = drs[0]["ad_code"].ToString();
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setAD_New function. Error: " + e.Message);
        }
        finally
        {
            //ddi = null;
        }
    }
    private void manageCollapsiblePanel()
    {
        if (Session["collapsed"] != null)
        {
            CollapsiblePanelExtender1.Collapsed = Convert.ToBoolean(Session["collapsed"].ToString());
            //Panel1.Enabled = !Convert.ToBoolean(Session["collapsed"].ToString());
        }

        //This piece of code was added to load a page with the side panel collapsed without interfeing the collapsible state of the panel.
        //Set the panel to visible false in the required page and the page will load with panel in a collapsed state
        //Added for Statement page by Jeya Prabha on 01-Dec-2009
        if (Panel1.Visible == false)
        {
            CollapsiblePanelExtender1.Collapsed = true;
            Panel1.Visible = true;
        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("PagesetWizard.aspx");
    }
    protected void menulink_Click(object sender, EventArgs e)
    {
        Response.Redirect("MenuPage.aspx");
    }
    private void deleteCustomLogo()
    {
        try
        {
            if (Session["company_afrowid"] != null)
            {
                DirectoryInfo di = new DirectoryInfo(Server.MapPath(".") + "\\Images\\CustomLogo");
                FileInfo[] fis = di.GetFiles(Session["company_afrowid"].ToString() + "*");
                if (fis.Length > 0)
                {
                    File.Delete(fis[0].FullName);
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in deleteCustomLogo: " + e.Message);
        }
        finally
        {
            
        }
    }
    protected void lb_logout_Click(object sender, EventArgs e)
    {
        deleteCustomLogo();
        string sRedirect = "";
        hdds = new security();
        if (hdds.allRightsForNGMODEL())
            sRedirect = "Logout.aspx?LG=index.aspx";
        else
            sRedirect = "Logout.aspx?LG=" + ConfigurationManager.AppSettings["LoginPage"]; //default.aspx";
        // Modified by 'Imran Gani' 13-Mar-2013, to get login page from web config
        LogWriter.WriteLog("Session End : " + DateTime.Now.ToString());
        //hdds.updateUserTheme();
        AuditLog AL = new AuditLog();
        AL.updateUserInCompany();
        AL = null;
        if (!Page.User.Identity.IsAuthenticated)
        {
            if (Page.Request.Cookies["ASP.NET_SessionId"] != null)
            {
                Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
            }
            for (int i = 0; i < Session.Count; i++) // Added by srivatsan June 22 2009
            {
                Session[i] = null;
            }
            Session.Abandon();
            LogWriter.WriteLog("Session Abandoned : " + DateTime.Now.ToString());
        }
        //if (Session != null)//sanal testing on June 12, 2009
        //{
        //    Session.Clear();
        //    Session.Abandon();            
        //    //Session
        //}
        if (sRedirect != "")
            Response.Redirect(sRedirect);
        else
            Response.Redirect("Logout.aspx");
    }

    protected void mnu_theme_MenuItemClick(object sender, MenuEventArgs e)
    {
        if (e.Item.Text != "")
        {
            Session["Theme"] = e.Item.Value + "Theme"; //Session["Theme"] = e.Item.Text + "Theme"; //change by Jeya Prabha on 17-Sep-2007
            Response.Redirect(HttpContext.Current.Request.Url.ToString());
        }
    }

    protected void lb_help_Click(object sender, EventArgs e)
    {

    }
    protected void lb_home_Click(object sender, EventArgs e)
    {
        Navigator ng = new Navigator();
        string retrn = ng.getUserHomePage();
        ng = null;
        Response.Redirect(retrn);
    }
    public void load_menuname(string strMenuRowId, ref string strfinal) //added by Prithi on 21-Aug-2008 to load navigation menu 
    {
        try
        {
            //string strtext;
            DataRow drmenu = hdds.hddb.GetTableRow("select menu_name,parent_menu_id from sy_mnu where af_row_id='" + strMenuRowId.Replace("'", "''") + "'");
            if (drmenu != null)
            {
                string strmenuname = CommonFunctions.SafeEncode(drmenu["menu_name"].ToString());
                string strparent1 = drmenu["parent_menu_id"].ToString();

                if (strparent1 != "" && strMenuRowId != strparent1)
                {

                    load_menuname(strparent1, ref strfinal);
                    string rtnavigate = navigate(strMenuRowId);
                    if (rtnavigate != "")
                    {
                        strfinal = strfinal + "&nbsp;<b>>></b>&nbsp;" + "<a href='" + rtnavigate + "' >" + strmenuname + "</a>";
                        return;
                    }
                    else
                    {
                        strfinal = strfinal + "&nbsp;<b>>></b>&nbsp;" + rtnavigate + strmenuname;
                        return;
                    }
                }
                else
                {
                    string rtnavigate = navigate(strMenuRowId);

                    if (rtnavigate != "")
                    {
                        strfinal = strfinal + "<a href='" + rtnavigate + "' >" + strmenuname + "</a>";
                        return;
                    }
                    else
                    {
                        strfinal = strfinal + rtnavigate + strmenuname;
                        return;
                    }
                }
                drmenu = null;

            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in load_menuname function. Error: " + e.Message);
        }


    }

    public string navigate(string strMenuRowId)//added by Prithi on 21-Aug-2008 to generate the url for navigation menu
    {
        string strMenuNavigateUrl = "";
        try
        {
            DataRow drurl = hdds.hddb.GetTableRow("select pageset_url_type,pageset_id,menu_click,pageset_url from sy_mnu where af_row_id='" + strMenuRowId.Replace("'", "''") + "'");
            if (drurl != null)
            {
                string strPagesetUrlType = drurl["pageset_url_type"].ToString();
                string strmenuclick = drurl["menu_click"].ToString();
                string strPagesetRowId = drurl["pageset_id"].ToString();
                string strPagesetUrl = "";
                if (strPagesetRowId != "")
                {
                    string strPagesetUrlParam = "?mn=" + strMenuRowId.ToString() + "&pgs_id=" + strPagesetRowId;

                    if (strmenuclick == "2" && strPagesetUrlType == "2")
                    {
                        strPagesetUrl = drurl["pageset_url"].ToString();
                        strMenuNavigateUrl = strPagesetUrl + strPagesetUrlParam;
                    }



                    else if (strPagesetUrlType == "3") // for external link there is no parameters 
                    {
                        if (!strPagesetUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                        {
                            strPagesetUrl = "http://" + strPagesetUrl;
                        }
                        strMenuNavigateUrl = strPagesetUrl;

                    }
                    else
                    {
                        strPagesetUrl = "DisplayGrid.aspx";
                        strMenuNavigateUrl = strPagesetUrl + strPagesetUrlParam;
                    }



                }


            }
            return strMenuNavigateUrl;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in navigate function. Error: " + e.Message);
            return strMenuNavigateUrl;
        }

    }

    private void getnavigatorURL()  // Added by srivatsan on June 22 2009 for getting home page URL
    {
        Navigator ngr = new Navigator();
        if (homepageURL == "")
        {
            homepageURL = ngr.getUserHomePage();
        }
        ngr = null;

    }
    private void getLogoutLink() // Added by srivatsan on June 22 2009 for getting logout URL
    {
        hdds = new security();
        string temp = getSessionLogoutURL();
        if (temp == "")
        {
            if (hdds.allRightsForNGMODEL())
                sRedirect = "Logout.aspx?LG=index.aspx";
            else
                sRedirect = "Logout.aspx?LG=" + ConfigurationManager.AppSettings["LoginPage"]; //default.aspx"; 
            // Modified by 'Imran Gani' 13-Mar-2013, to get login page from web config
        }
        else//Sanal on 09 Dec 2010
        {
            sRedirect = "Logout.aspx?LG=" + Server.UrlEncode(temp);
        }
    }
    private string getSessionLogoutURL()//Sanal on 09 Dec 2010
    {
        string ret = "";
        if (Session != null)
        {
            if (Session["logoutURL"] != null)//this will be set from client apps like EC
                ret = Session["logoutURL"].ToString(); 
        }
        return ret;
    }
    private void GetFeedBackEmailIds()
    {
        DataRow[] drrDynamicHeader = null;
        DataRow[] drrDynamicTitle = null;
        DataRow[] drrlink = null;
        try
        {

            rbtnadmin.Attributes.Add("onClick", "javascript:Adminclick();");
            rbtnuser.Attributes.Add("onClick", "javascript:UserClick();");


            HDDatabase HDD = new HDDatabase();
            //string sql = "select mem_value2 as sv,mem_value3 as dv from sy_acr_mem where af_row_id = 'b13034b44961ff77'";
            //string sql = "select * from sy_acr_mem where acr_id = '48e3dc27301a23e9' order by mem_seq";
            string sql = "select af_row_id,mem_name,mem_value1,mem_value2,mem_value3 from sy_acr_mem where acr_id = '48e3dc27301a23e9' order by mem_seq";
            DataTable dsacrmem = new DataTable();
            dsacrmem = HDD.GetDataTable(sql);
            drrDynamicHeader = dsacrmem.Select("af_row_id='a1c84c7fd520718U'");
            drrDynamicTitle = dsacrmem.Select("af_row_id='c93952b1519815be'");
            drrlink = dsacrmem.Select("af_row_id='1e9ae894add27776'");
            if (dsacrmem != null)
            {
                if (dsacrmem.Rows.Count > 0)
                {
                    DataRow[] drr = null;

                    drr = dsacrmem.Select("af_row_id='462240c767cc6c5a'");
                    if (drr.Length > 0)
                    {
                        if (drr[0]["mem_value1"].ToString().ToLower().Trim() == "true" || drr[0]["mem_value1"].ToString().ToLower().Trim() == "1")
                        {
                            pantoemail.Visible = true;
                            //tblfeedback.Visible = true;

                            drr = dsacrmem.Select("af_row_id = 'd193010cb846f735'");
                            bool showcompadmin = false;
                            string compadmindisplayname = "";
                            if (drr.Length > 0)
                            {
                                if (drr[0]["mem_value1"].ToString().ToLower().Trim() == "true" || drr[0]["mem_value1"].ToString().ToLower().Trim() == "1")
                                {
                                    showcompadmin = true;
                                    compadmindisplayname = drr[0]["mem_value2"].ToString().Trim();

                                }

                            }


                            drr = dsacrmem.Select("af_row_id = 'b13034b44961ff77'");
                            if (drr.Length > 0)
                            {
                                hfadmin.Value = drr[0]["mem_value2"].ToString().Trim();
                                rbtnadmin.Text = drr[0]["mem_value3"].ToString().Trim() == "" ? drr[0]["mem_value2"].ToString().Trim() : drr[0]["mem_value3"].ToString().Trim();
                                rbtnadmin.ToolTip = hfadmin.Value;
                            }



                            string currentaf_row_id = Session["user_afrowid"].ToString();
                            DataSet ds = HDD.GetDataset("select first_name,last_name,email_id,user_id from sy_usr where af_row_id = '" + "650a333596bbf348" + "'");

                            if (ds != null)
                            {
                                if (ds.Tables.Count > 0)
                                {
                                    if (ds.Tables[0].Rows.Count > 0)
                                    {
                                        string firstname = ds.Tables[0].Rows[0]["first_name"].ToString();
                                        string lastname = ds.Tables[0].Rows[0]["last_name"].ToString();

                                        string emailid = ds.Tables[0].Rows[0]["email_id"].ToString();
                                        drr = dsacrmem.Select("af_row_id='fb2a35dfafaf1323'");
                                        bool bEmailId = true;
                                        if (drr.Length > 0)
                                        {
                                            bEmailId = bool.Parse(drr[0]["mem_value1"].ToString());
                                        }

                                        if (bEmailId)
                                        {
                                            emailid = ds.Tables[0].Rows[0]["email_id"].ToString();
                                        }
                                        else
                                        {
                                            emailid = ds.Tables[0].Rows[0]["user_id"].ToString();
                                        }
                                        if (emailid != "")
                                        {
                                            string displayname = firstname + " " + lastname;
                                            if (showcompadmin)
                                            {
                                                rbtnuser.Text = compadmindisplayname.Trim() != "" ? compadmindisplayname.Trim() : displayname;
                                                rbtnuser.ToolTip = displayname;

                                            }
                                            else
                                            {
                                                rbtnuser.Text = displayname;
                                                rbtnuser.ToolTip = displayname;
                                            }
                                            hfuser.Value = emailid;
                                        }
                                        else
                                        {
                                            rbtnuser.Visible = false;
                                        }


                                    }
                                }
                            }


                        }
                        else
                        {
                            pantoemail.Visible = false;
                            //                            tblfeedback.Visible = false;
                        }
                    }

                }
            }
            //Changes made by bala for Adding values dynamically on 16Mar12
            if (drrDynamicTitle.Length > 0)
            {
                lbltitle.Text = drrDynamicTitle[0]["mem_value1"].ToString();
            }
            if (drrDynamicHeader.Length > 0)
            {
                lblheader.Text = drrDynamicHeader[0]["mem_value1"].ToString();
            }
            if (drrlink.Length > 0)
            {
                Footerlink.Visible = Convert.ToBoolean(drrlink[0]["mem_value1"].ToString());
                Footerlink.Text = drrlink[0]["mem_value2"].ToString();
                Footerlink.NavigateUrl = drrlink[0]["mem_value3"].ToString();
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetFeedBackEmailIds :" + ex.Message);
        }
        finally
        {
            drrDynamicHeader = null;
            drrDynamicTitle = null;
            drrlink = null;
        }
    }

    //Added by srivatsan on Sep 30 2009 for Next Step and Related content in Page Header
    private void CreateAdditionalSectioninHeader()
    {
        try
        {
            lbl_appmaster_nextstep.Text = "&nbsp;<img style=\"vertical-align:bottom\" src=\"Images/next_step.gif\" alt=\"Next Step\" /> <span style=\"font-size: 8pt; vertical-align:bottom\" class=\"defaultFont\">Next Step</span>";//"<img src=\"Images/next_step.GIF\"></img>";
            lbl_appmaster_relatedinfo.Text = "&nbsp;&nbsp;<img style=\"vertical-align:bottom\" src=\"Images/rel_info.gif\" alt=\"Related Information\" /> <span style=\"font-size: 8pt; vertical-align:bottom\" class=\"defaultFont\">Related Info</span>";//"<img src=\"Images/info.GIF\"></img>";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CreateAdditionalSectionInHeader :" + ex.Message);
        }
        finally
        {

        }
    }

    /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
    protected void dismiss_Click(object sender, EventArgs e)
    {
        GenerateAlerts GA = new GenerateAlerts();
        int left = 0;
        int top = 0;
        if (hd_left.Value != "")
            left = Convert.ToInt16(hd_left.Value);
        if (hd_top.Value != "")
            top = Convert.ToInt16(hd_top.Value);
        try
        {
            foreach (GridViewRow row in Reminders.Rows)
            {
                CheckBox cbox = (CheckBox)row.Cells[0].Controls[0];
                if (cbox != null && cbox.Checked)
                {
                    string row_id = row.Cells[0].Text;
                    GA.DismissTask(row_id);
                    ShowReminderList.Style.Add("display", "block");
                    ShowReminderList.Style.Add("left", left.ToString() + "px");
                    ShowReminderList.Style.Add("top", top.ToString() + "px");
                    LoadReminders();
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Dismiss Task : " + ex.Message);
        }
        finally
        {
            GA = null;
            if (Reminders.Rows.Count <= 0)
                ShowReminderList.Style.Add("display", "none");
        }
    }

    protected void defer_Click(object sender, EventArgs e)
    {
        GenerateAlerts GA = new GenerateAlerts();
        int left = 0;
        int top = 0;
        try
        {
            if (hd_left.Value != "")
                left = Convert.ToInt16(hd_left.Value);
            if (hd_top.Value != "")
                top = Convert.ToInt16(hd_top.Value);
            if (ddl_deferred.SelectedIndex != 0)
            {
                foreach (GridViewRow row in Reminders.Rows)
                {
                    CheckBox cbox = (CheckBox)row.Cells[0].Controls[0];
                    if (cbox != null && cbox.Checked)
                    {
                        string row_id = row.Cells[0].Text;
                        if (ddl_deferred.SelectedValue != "")
                        {

                            GA.DeferTask(row_id, ddl_deferred.SelectedValue);
                            ShowReminderList.Style.Add("display", "block");
                            ShowReminderList.Style.Add("left", left.ToString() + "px");
                            ShowReminderList.Style.Add("top", top.ToString() + "px");
                            LoadReminders();
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Defer Task : " + ex.Message);
        }
        finally
        {
            GA = null;
            if (Reminders.Rows.Count <= 0)
                ShowReminderList.Style.Add("display", "none");
            ddl_deferred.SelectedIndex = 0;
        }
    }
    protected void update_Click(object sender, EventArgs e)
    {
        //UP_count.Update();
        LoadReminders();
        //UP_count.Update();
    }

    //Added by 'Imran Gani' on 07-Jan-2014, for complete button
    protected void task_completed_Click(object sender, EventArgs e)
    {
        GenerateAlerts GA = new GenerateAlerts();
        int left = 0;
        int top = 0;
        if (hd_left.Value != "")
            left = Convert.ToInt16(hd_left.Value);
        if (hd_top.Value != "")
            top = Convert.ToInt16(hd_top.Value);
        try
        {
            foreach (GridViewRow row in Reminders.Rows)
            {
                CheckBox cbox = (CheckBox)row.Cells[0].Controls[0];
                if (cbox != null && cbox.Checked)
                {
                    string row_id = row.Cells[0].Text;
                    GA.CompleteTask(row_id);
                    ShowReminderList.Style.Add("display", "block");
                    ShowReminderList.Style.Add("left", left.ToString() + "px");
                    ShowReminderList.Style.Add("top", top.ToString() + "px");
                    LoadReminders();
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Dismiss Task : " + ex.Message);
        }
        finally
        {
            GA = null;
            if (Reminders.Rows.Count <= 0)
                ShowReminderList.Style.Add("display", "none");
        }
    }
    /********* End of Task & Alerts *********/
}
